package com.boot.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.boot.realm.SimpleRealms;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.session.mgt.eis.MemorySessionDAO;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean filterFactoryBean(@Qualifier("manager") DefaultWebSecurityManager manager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(manager);
        Map<String,String> map = new HashMap<>();
        //匿名可以访问的内容
        map.put("/test","anon");
        map.put("/login","anon");
        map.put("/unauthorized","anon");
        map.put("/login_finish","anon");
        // 其他的都需要授权
        map.put("/**","authc");

        factoryBean.setFilterChainDefinitionMap(map);
        //成功页面
        factoryBean.setSuccessUrl("/success");
        //设置登录页面
        factoryBean.setLoginUrl("/login");
        //未授权页面
        factoryBean.setUnauthorizedUrl("/unauthorized");
        return factoryBean;
    }

    @Bean
    public DefaultWebSecurityManager manager(@Autowired SimpleRealms myRealm,@Autowired SessionManager sessionManager){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(myRealm);
        manager.setSessionManager(sessionManager);
        return manager;
    }

    //session会话
    @Bean
    public MemorySessionDAO sessionDAO(){
        MemorySessionDAO sessionDAO = new MemorySessionDAO();
        return sessionDAO;
    }

    //session会话管理
    @Bean
    public SessionManager sessionManager(@Autowired MemorySessionDAO sessionDAO){
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setSessionDAO(sessionDAO);
        return sessionManager;
    }

    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }

}